﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;

namespace Curry.Forum.Infrastructure
{
    public class DBHelper
    {
        public DBHelper()
        {
        }

        public IEnumerable<T> Query<T>(string sql, object parameters = null, bool isRead = true) where T : class
        {
            if (string.IsNullOrWhiteSpace(sql))
            {
                throw new ArgumentNullException("sql");
            }

            IDbConnection conn = null;
            try
            {
                using (conn = DataSource.GetConnection())
                {
                    return conn.Query<T>(sql, parameters);
                }
            }
            catch (Exception )
            {
                throw;
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }


        public T ExecuteScalar<T>(string sql, object param = null, bool isRead = true)
        {
            if (string.IsNullOrEmpty(sql))
            {
                throw new ArgumentNullException(nameof(sql));
            }
            IDbConnection conn = null;
            try
            {
                using (conn = DataSource.GetConnection())
                {
                    return conn.ExecuteScalar<T>(sql, param);
                }
            }
            catch (Exception )
            {
                throw;
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }

        public int ExecuteWriteSql(string sql, object parameters = null, bool isRead = false, IDbTransaction tran = null)
        {
            if (string.IsNullOrWhiteSpace(sql))
            {
                throw new ArgumentNullException("sql");
            }

            IDbConnection conn = null;
            try
            {
                using (conn = DataSource.GetConnection())
                {
                    return conn.Execute(sql, parameters, tran);
                }
            }
            catch (Exception )
            {
                throw;
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
    }
}
